<template>
  <a-modal
    title="修改密码"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirmLoading="loading"
  >
    <a-form-item label="旧密码">
      <a-input-password v-model="form.old_password" placeholder="请输入旧密码" />
    </a-form-item>
    <a-form-item label="新密码">
      <a-input-password v-model="form.new_password" placeholder="请输入新密码" />
    </a-form-item>
    <a-form-item label="确认密码">
      <a-input-password v-model="confirmPassword" placeholder="请再次输入新密码" />
    </a-form-item>
  </a-modal>
</template>

<script>
import { apiChangePassword } from '@/api/featch'
import { Base64 } from '@/assets/js/base64'

export default {
  name: 'ChangePassword',
  data() {
    return {
      visible: false,
      loading: false,
      form: {
        person_id: '',
        old_password: '',
        new_password: ''
      },
      confirmPassword: ''
    }
  },
  methods: {
    showModal() {
      this.visible = true
      this.form = {
        person_id: '',
        old_password: '',
        new_password: ''
      }
      this.confirmPassword = ''
      // 获取用户ID
      const personInfo = JSON.parse(window.sessionStorage.getItem('person_info'))
      if (personInfo) {
        this.form.person_id = personInfo.person_id
      }
    },
    handleCancel() {
      this.visible = false
    },
    async handleOk() {
      if (!this.form.old_password) {
        this.$message.warning('请输入旧密码')
        return
      }
      if (!this.form.new_password) {
        this.$message.warning('请输入新密码')
        return
      }
      if (!this.confirmPassword) {
        this.$message.warning('请确认新密码')
        return
      }
      if (this.form.new_password !== this.confirmPassword) {
        this.$message.warning('两次输入的密码不一致')
        return
      }

      this.loading = true
      try {
        const params = {
          ...this.form,
          old_password: Base64.encode(this.form.old_password),
          new_password: Base64.encode(this.form.new_password)
        }
        const res = await apiChangePassword(params)
        if (res.code === 200) {
          this.$message.success('修改密码成功，请重新登录')
          this.visible = false
          // 清除登录信息并跳转到登录页
          window.sessionStorage.clear()
          window.localStorage.removeItem('password')
          this.$router.push('/login')
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        this.$message.error(error.message)
      } finally {
        this.loading = false
      }
    }
  }
}
</script> 